<?php

namespace App\Http\Controllers\Api;

use App\Events\addLog;
use App\Http\Controllers\Controller;

use App\Http\Resources\AdminUpdateResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\AdminResource;

class AdminController extends Controller
{

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $models = User::query()->orderByDesc('id')->paginate();
        return AdminUpdateResource::collection($models);
    }

    /**
     * @param Request $request
     * @return AdminUpdateResource
     */
    public function store(Request $request)
    {
        $model = new User();
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        $model->fill($data);
        $model->api_token = str_random(40);
        $model->save();
        event(new addLog(Auth::user(),'添加'.$model->name));
        return new AdminUpdateResource($model);
    }

    /**
     * @param Request $request
     * @param $id
     * @return AdminUpdateResource
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();
        if (!empty($data['password'])) {
            $data['password'] = bcrypt($data['password']);
        }
        $model = $this->findModel($id);
        $model->fill($data);
        $model->save();
        event(new addLog(Auth::user(),'修改了'.$model->name.'的信息'));
        return new AdminUpdateResource($model);
    }

    /**
     * @param $id
     * @return AdminUpdateResource
     */
    public function show($id)
    {
        $model = $this->findModel($id);
        return new AdminUpdateResource($model);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        event(new addLog(Auth::user(),'删除了'.$model->name));
        $model->delete();
        return response()->json(['state'=>'success']);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function findModel($id){
        return User::query()->where('id',$id)->first();
    }
    /**
     * 获取当前登录用户信息
     * @return mixed
     */
    public function getProfile()
    {
        $authUser = Auth::user();
        return new AdminResource($authUser);
    }
}
